package com.candy.service;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author donglin
 * @Title:
 * @类名: WebSocket
 * @date 2020/10/15
 */
//ServerEndpoint注解：使用ServerEndpoint注解，前台进行websocket协议进行访问时，找到的类
@Component
@ServerEndpoint("/websocket")
public class WebSocket {
//    表示与某个用户的连接，通过它给客户端进行发送数据
    private Session session;
//    存放每个客户端对应的server对象，可以使用Set来进行存储
    private static CopyOnWriteArraySet<WebSocket> webSockets=new CopyOnWriteArraySet<>();
   @OnOpen
    public void onOpen(Session session){
       this.session=session;
       webSockets.add(this);
       System.out.println("我已经创建好连接了");

    }
    @OnClose
    public void onClose(){
       webSockets.remove(this);
        System.out.println("断开连接了，拜拜");

    }
    @OnError
    public void onError(Throwable throwable){
        System.out.println("叮叮~发生异常");
    }
    @OnMessage
    public void onMessage(String message){
        System.out.println(message);

    }

//    进行消息发送的方法
    public void sendMessage(String messaage){
        for (WebSocket websocket:webSockets) {
            try {
                websocket.session.getBasicRemote().sendText(messaage);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }






}
